package com.font.web.system;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.font.bean.Face;
import com.font.bean.ParamResult;
import com.font.bean.result.Result;
import com.font.redis.RedisCache;
import com.font.service.LoginService;
import com.font.utils.CreateImageCode;
import io.swagger.annotations.Api;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.request.AuthGiteeRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/system")
@Api("email验证接口")
@CrossOrigin
public class LoginController {

    @Autowired
    LoginService loginService;

    @Autowired
    private JavaMailSenderImpl mailSender;

    @Value("${spring.mail.username}")
    private String emailFrom;


    @Autowired
    RedisCache redisCache;

    @ResponseBody
    @GetMapping("/sent")
    public Result faceVef(@RequestParam(value = "email") String email){
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        Random random = new Random();
        int code = random.nextInt(9000) + 1000;
        String codeMsg="您的验证码是"+code+"，15分钟内有效";
        redisCache.setCacheObject("emailCode",code,15, TimeUnit.MINUTES);
        mailMessage.setFrom(emailFrom);
        mailMessage.setTo(email);
        mailMessage.setText(codeMsg);
        mailMessage.setSubject("邮箱验证码");
        mailSender.send(mailMessage);
        System.out.println("====完成发送！====");
        return loginService.sent(email);
    }
    @ResponseBody
    @PostMapping("/login")
    public Result faceVef(@RequestBody ParamResult parm){
        System.err.println("进入");
        System.err.println(loginService.login(parm));
        return loginService.login(parm);
    }
    @ResponseBody
    @RequestMapping(value = "/checkCode")
    public void checkCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        CreateImageCode vCode = new CreateImageCode(130, 38, 5, 10);
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        String code = vCode.getCode();
        redisCache.setCacheObject("code",code,15, TimeUnit.MINUTES);
        vCode.write(response.getOutputStream());
    }


        @ResponseBody
        @RequestMapping("/render")
        public void renderAuth(HttpServletResponse response) throws IOException {
            AuthRequest authRequest = getAuthRequest();
            response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
        }
        @ResponseBody
        @RequestMapping("/callback")
        public Object login(AuthCallback callback) {
            AuthRequest authRequest = getAuthRequest();
            AuthResponse login = authRequest.login(callback);
            JSONObject parse = JSONObject.parse(JSON.toJSONString(login));
            Object gieeUser = parse.get("data");
            JSONObject user = JSONObject.parse(JSON.toJSONString(gieeUser));
            Object avatar = user.get("avatar");
            Object nickname = user.get("nickname");
            Object email = user.get("email");
            Map<String,Object> map=new HashMap<>();
            map.put("avatar",avatar);map.put("nickname",nickname);map.put("email",email);
            return map;
        }
        private AuthRequest getAuthRequest() {
            return new AuthGiteeRequest(AuthConfig.builder()
                    .clientId("ed8db7a16332fff37b575edd66c0ef87bcb9fe710da836dad1f782ddbaf23918")
                    .clientSecret("a84e3d9a4c208f5c165fa177f7742591478539daccd1db3bc3a029f74a74357d")
                    .redirectUri("http://localhost:8089/system/callback")
                    .build());
    }
    @ResponseBody
    @PostMapping("/register")
    public Result register(@RequestBody ParamResult parm){
        return loginService.register(parm);
    }
    @GetMapping("/checkUsername")
    public Boolean checkUsername(String userName){
        Face face= loginService.checkUsername(userName);
        return StringUtils.isEmpty(face) ?false:true;
    }

    @ResponseBody
    @PostMapping("/getToken")
    public Result getToken(@RequestBody ParamResult parm){
        return loginService.getToken(parm);
    }
}
